# -*- coding:UTF-8 -*-
import os,sys
import cv2
import random
import time
import config,logger 
import win32gui, win32ui, win32con,win32api
from ctypes import *
hWnd = win32gui.FindWindow("Win32Window0","阴阳师-网易游戏")
left, top, right, bot = win32gui.GetWindowRect(hWnd)
width = right - left
height = bot - top
#返回句柄窗口的设备环境，覆盖整个窗口，包括非客户区，标题栏，菜单，边框
hWndDC = win32gui.GetWindowDC(hWnd)
#创建设备描述表
mfcDC = win32ui.CreateDCFromHandle(hWndDC)

def get_screen():
    # windll.user32.SetCursorPos(120,345)
    check()
    # signedIntsArray = saveBitMap.GetBitmapBits(True)
    #创建内存设备描述表
    saveDC = mfcDC.CreateCompatibleDC()
    #创建位图对象准备保存图片
    saveBitMap = win32ui.CreateBitmap()
    #为bitmap开辟存储空间
    saveBitMap.CreateCompatibleBitmap(mfcDC,width,height)
    #将截图保存到saveBitMap中
    saveDC.SelectObject(saveBitMap)
    #保存bitmap到内存设备描述表
    saveDC.BitBlt((0,0), (width,height), mfcDC, (0, 0), win32con.SRCCOPY)
    saveBitMap.SaveBitmapFile(saveDC,config.tmpPath+config.tmpImg)
    img= cv2.imread(config.tmpPath+config.tmpImg,0)
    return img
def check():
    if width<500:
        logger.info('请勿缩小窗口')
        time.sleep(1)
        sys.exit()    
def matchEnd(img1, template):
   
    """img1代表待匹配图像, img2代表模板"""
    res = cv2.matchTemplate(img1,template,cv2.TM_CCOEFF_NORMED)
    print(res.max())
    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
    left_top = max_loc  # 左上角
    print(left_top,'\n')

def match(img, template):
    """img1代表待匹配图像, img2代表模板"""
    res = cv2.matchTemplate(img,template,cv2.TM_CCOEFF_NORMED)
    maxres = res.max()
    if maxres>0.8:
        return 1
    else:
        return 0
#返回匹配位置        
def lmatch(img,template):
    res = cv2.matchTemplate(img,template,cv2.TM_CCOEFF_NORMED)
    maxres=res.max()
    if maxres>0.8:
        min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
        theight, twidth = template.shape[:2]
        cv2.rectangle(template,min_loc,(min_loc[0]+twidth,min_loc[1]+theight),(0,0,225),2)
        return {'max':max_loc,'min':min_loc}
    else:
        return 0
def get_randxy(x, y):
    """产生一个在x,y二维区域内的随机位置,x,y为两个元素的列表，变量范围"""
    xc = random.randint(x[0], x[1])
    yc = random.randint(y[0], y[1])
    return xc,yc

def get_randtime(a, b):
    """产生a,b间的随机时间延迟"""
    time.sleep(random.uniform(a, b))

def click(x, y):
    """输入两个二维列表，表示要点击的位置的x坐标，y坐标"""
    # cmd_click = config.rootPath+'/adb shell input tap {} {}'.format(x, y)
    # os.system(cmd_click)   
    check()
    logger.info("当前点击的位置（"+str(x)+","+str(y)+"）")
    tmp=win32api.MAKELONG(x,y)
    # win32gui.SendMessage(hWnd, win32con.WM_MOUSEMOVE,0,tmp)
    win32gui.SendMessage(hWnd, win32con.WM_LBUTTONDOWN,win32con.MK_LBUTTON,tmp)
    win32gui.SendMessage(hWnd, win32con.WM_LBUTTONUP,win32con.MK_LBUTTON,tmp)
def midWheel(count=1):
    for i in range(0,count):
        print(1111)
        # win32gui.HookMessage(hWnd,win32con.WM_MOUSEWHEEL)
        win32api.mouse_event(win32con.MOUSEEVENTF_WHEEL, 0, 0, -100)    
    

